var formidable = require('formidable');
var fs = require('fs'),
    TITLE = 'formidable上传示例',
    domain = "http://localhost:8089/";
    AVATAR_UPLOAD_FOLDER = '/img/';
    AVATAR_UPLOAD_FOLDER1 = '/video/';


    var form = new formidable.IncomingForm();   //创建上传表单
    form.encoding = 'utf-8';        //设置编辑
    //form.uploadDir = 'public' + AVATAR_UPLOAD_FOLDER;
    form.uploadDir = '/home/fruit_shop/public/dist/image/';     //设置上传目录
    form.keepExtensions = true;     //保留后缀
    form.maxFieldsSize = 4 * 1024 * 1024;   //文件大小
     form.parse(req, function(err, fields, files) {
        if (err) {
        res.locals.error = err;
        res.send({
            status:4,
            msg:'上传失败',
            data:[]
        })
        return;
        }
        console.log(files);
        
        console.log('path',files.file.path);
        var extName = '';  //后缀名
        switch (files.file.type) {
        case 'image/pjpeg':
            extName = 'jpg';
            break;
        case 'image/jpeg':
            extName = 'jpg';
            break;
        case 'image/png':
            extName = 'png';
            break;
        case 'image/x-png':
            extName = 'png';
            break;
        }
        console.log(form.uploadDir);
        console.log(`you are right`);
        if(extName==null){
        res.locals.error = '只支持png和jpg格式图片';
        // res.render({ title: TITLE });
         return;
        }
        
        var avatarName = Math.random() + '.' + extName;
        //图片写入地址；
        var newPath = form.uploadDir + avatarName;
        //显示地址；
        var showUrl = domain + AVATAR_UPLOAD_FOLDER + avatarName;
        //console.log(showUrl)
        console.log("newPath",newPath);

        fs.renameSync(files.file.path, newPath);  //重命名
        res.send({
             status:3,
             msg:'上传成功',
             data:showUrl
        })
           
    });
    return ;